package com.zwy.service.impl;

import com.zwy.constants.RedisConst;
import com.zwy.service.PublicService;
import com.zwy.utils.RedisCache;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zwy
 * @version 1.0
 * @description: PublicServiceImpl
 * @date 2025/9/22 14:15
 */
@Service
@Slf4j
public class PublicServiceImpl implements PublicService {
    @Resource
    private RedisCache redisCache;

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Value("${spring.rabbitmq.routingKey.email}")
    private String routingKey;

    @Value("${spring.rabbitmq.exchange.email}")
    private String exchange;
    /**
     * 邮箱通知
     *
     * @param type    邮箱类型
     * @param email   邮箱地址
     * @param content 邮箱内容
     */
    @Override
    public void sendEmail(String type, String email, Map<String, Object> content) {
        // 发送邮件
        if (content != null) {
            content.put("email", email);
            content.put("type", type);
            rabbitTemplate.convertAndSend(exchange, routingKey, content);
        } else rabbitTemplate.convertAndSend(exchange, routingKey, Map.of("email", email, "type", type));

    }
    @Override
    public String registerEmailVerifyCode(String type, String email) {
        //线程锁
        synchronized (email.intern()) {
            //生成6位数验证码
            String verifyCode = String.valueOf((int) ((Math.random() * 9 + 1 ) * 100000));
            //将验证码存入redis缓存
            redisCache.setCacheObject(RedisConst.VERIFY_CODE + type + RedisConst.SEPARATOR + email,verifyCode,RedisConst.VERIFY_CODE_EXPIRATION, TimeUnit.MINUTES);
            // 发送邮件
            Map<String, Object> senEmail = Map.of("email", email, "code", verifyCode, "type", type);
            rabbitTemplate.convertAndSend(exchange, routingKey, senEmail);

            return "验证码已发送，请在邮箱中查收";
        }

    }

}
